// npm install --save-dev gulp del circe gulp-sftp minimist

// 清理dist
// gulp clean

// 清理当前项目阿里云test环境
// gulp cleanOSS --env test

// 清理当前项目阿里云production环境
// gulp cleanOSS --env production

// 编译打包并上传到阿里云
// gulp upload

// 编译打包部署到test服务器
// gulp publish --env test

// 编译打包部署到production服务器
// gulp publish --env production

const gulp = require('gulp')
const minimist = require('minimist')
const del = require('del')
const webpack = require('webpack')
const alioss = require('circe/gulp/alioss')
const sftp = require('gulp-sftp')

const webpackConfig = require('./build/webpack.prod.conf')
const gulpConf = require('./gulpconf.json')
const timeVersion = Date.now()

gulp.task('env', () => {
  const env = process.env.NODE_ENV = minimist(process.argv).env
  console.log('## 当前环境：', env || '无')
})

gulp.task('clean', () => {
  console.log('## 清空工作区...')
  return del(['dist'])
})

gulp.task('cleanOSS', ['env'], () => {
  const env = process.env.NODE_ENV
  const prefix = gulpConf.appName + '/' + env
  if (!env) throw new Error('Missing NODE_ENV!')
  console.log('## 清空阿里云oss：', prefix)
  return alioss.clean(Object.assign(gulpConf.oss, {prefix}))
})

gulp.task('build', ['clean'], (done) => {
  const env = process.env.NODE_ENV
  if (env) {
    const ossUrl = 'http://' + gulpConf.oss.bucket + '.' + gulpConf.oss.region + '.aliyuncs.com'
    const appName = gulpConf.appName
    const publicPath = [ossUrl, appName, env, timeVersion].join('/') + '/'
    webpackConfig.output.publicPath = publicPath
    console.log('## webpack静态资源将发布到 --> ' + publicPath)
  }

  console.log('## webpack编译中...')
  webpack(webpackConfig, (err, stats) => {
    if (err) return done(err)
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n')
    console.log('## webpack编译完成！')
    done()
  })
})

gulp.task('upload', ['build'], (done) => {
  const appName = gulpConf.appName
  const env = process.env.NODE_ENV || 'development'
  const ossConf = Object.assign(gulpConf.oss, {
    prefix: [appName, env, timeVersion].join('/')
  })
  return gulp.src('dist/**').pipe(alioss.upload(ossConf))
})

gulp.task('deploy', ['upload'], () => {
  const env = process.env.NODE_ENV
  if (!env) throw new Error('Missing NODE_ENV')

  const ftpConf = gulpConf.ftp[env]
  console.log('## 正在部署到远端服务器（' + ftpConf.host + ':' + ftpConf.remotePath + '）...')
  return gulp.src('dist/index.html')
    .pipe(sftp(ftpConf))
})

gulp.task('publish', ['env', 'deploy'], () => {
  console.log('## 部署完成！')
})
